package com.ch999.detect.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ch999.commonUI.UITools;
import com.ch999.detect.R;
import com.ch999.detect.View.NewDetectView;
import com.ch999.detect.View.activity.CommerActivity;
import com.ch999.detect.View.activity.NewDetectActivity;
import com.ch999.detect.mode.bean.DialogCustomMode;
import com.ch999.detect.mode.bean.GoodsBjgz;
import com.ch999.detect.utils.AudioPlayer;
import com.ch999.detect.utils.CommUtils;
import com.ch999.detect.utils.DeviceUtils;
import com.ch999.detect.utils.NetworkUtils;
import com.ch999.detect.utils.RecordButton;
import com.scorpio.mylib.Routers.MDRouters;
import com.scorpio.mylib.Tools.Tools;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;
import com.wei.android.lib.fingerprintidentify.base.BaseFingerprint;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;

import static com.ch999.detect.utils.DeviceUtils.getTotalInternalMemorySize;

/**
 * NewDetectActivity 的控制层
 * Created by ch999android on 2017/12/27.
 */

public class NewDetectPresenter {
    private final AudioPlayer mAudioPlayer;
    NewDetectView mView;
    Activity context;
    LayoutInflater inflater;

    int soundIndex;//播放声音下标


    boolean isPause;
    public String mName;
    public View mView1;

    public Handler mHandler;
    private FingerprintIdentify mFingerprintIdentify;

    public boolean isPause() {
        return isPause;
    }

    public void setPause(boolean pause) {
        isPause = pause;
    }

    private int[] sounds = new int[]{R.raw.zero, R.raw.one, R.raw.two, R.raw.three,
            R.raw.four, R.raw.five, R.raw.six, R.raw.serven, R.raw.eight, R.raw.nine};//音频文件

    boolean wifiListener, chargeListener, GPSListener, Blotetooh, senser, callListener,
            volumekeyUP, volumekeyDOWN, screenView, ZNZCheck, TLYChekc, isSeeting, isAccount, isClickScreen = false;//是否为wifi广播监听状态m

    //是否支持的硬件
    boolean TLY = true;

    public boolean isScreenView() {
        return screenView;
    }

    public void setScreenView(boolean screenView) {
        this.screenView = screenView;
    }

    public boolean isVolumekeyUP() {
        return volumekeyUP;
    }

    public void setVolumekeyUP(boolean volumekeyUP) {
        this.volumekeyUP = volumekeyUP;
    }

    public boolean isZNZCheck() {
        return ZNZCheck;
    }

    public void setZNZCheck(boolean ZNZCheck) {
        this.ZNZCheck = ZNZCheck;
    }

    public boolean isVolumekeyDOWN() {
        return volumekeyDOWN;
    }

    public void setVolumekeyDOWN(boolean volumekeyDOWN) {
        this.volumekeyDOWN = volumekeyDOWN;
    }

    public boolean isWifiListener() {
        return wifiListener;
    }

    public void setWifiListener(boolean wifiListener) {
        this.wifiListener = wifiListener;
    }

    public boolean isChargeListener() {
        return chargeListener;
    }

    public void setChargeListener(boolean chargeListener) {
        this.chargeListener = chargeListener;
    }


    public boolean isSenser() {
        return senser;
    }

    public void setSenser(boolean senser) {
        this.senser = senser;
    }

    public boolean isBlotetooh() {
        return Blotetooh;
    }

    public void setBlotetooh(boolean blotetooh) {
        Blotetooh = blotetooh;
    }

    public boolean isGPSListener() {
        return GPSListener;
    }

    public void setGPSListener(boolean GPSListener) {
        this.GPSListener = GPSListener;
    }

    public boolean isCallListener() {
        return callListener;
    }

    public void setCallListener(boolean callListener) {
        this.callListener = callListener;
    }

    public boolean isSeeting() {
        return isSeeting;
    }

    public void setSeeting(boolean seeting) {
        isSeeting = seeting;
    }

    public boolean isClickScreen() {
        return isClickScreen;
    }

    public void setClickScreen(boolean clickScreen) {
        isClickScreen = clickScreen;
    }

    public boolean isAccount() {
        return isAccount;
    }

    public void setAccount(boolean account) {
        isAccount = account;
    }

    public NewDetectPresenter(NewDetectActivity mView, Activity context) {
        this.mView = mView;
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        mAudioPlayer = new AudioPlayer(context);

    }

    public boolean isTLYChekc() {
        return TLYChekc;
    }

    public void setTLYChekc(boolean TLYChekc) {
        this.TLYChekc = TLYChekc;
    }


    public void setHandler(Handler handler) {
        mHandler = handler;
    }

    public void setTLY(boolean TLY) {
        this.TLY = TLY;
    }

    /**
     * 根据不同的检测项加载不同的布局和功能
     *
     * @param attrBean
     * @return
     */
    public void startDetecting(GoodsBjgz.AttrBean attrBean, boolean isDetectOver) {
        View view;
        Fucation inflate;
        String name = attrBean.getTpname();
        switch (name) {
            case "GPS":
                if (isDetectOver) {
                    //检测完成，选择
                    mView.showAnyDialog(attrBean);
                    return;
                }
                inflate = getInflate();
                inflate.tvFucation.setText("请打开GPS开关");
                inflate.imgIcon.setImageResource(R.mipmap.icon_gps);


                checkGPS(name, inflate.rootView);
                return;
//
            case "麦克风":
                if (isDetectOver) {
                    //检测完成，选择
                    mView.showAnyDialog(attrBean);
                    return;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        checkVideo();
                    }
                }, 500);
//
                return;

            case "指南针":
                if (isDetectOver) {
                    //检测完成，选择
                    mView.showAnyDialog(attrBean);
                    return;
                }
                if (!TLY) {
                    mView.detectSuccess(0);
                    return;
                }
                final int count = 3;
                Observable.interval(0, 1, TimeUnit.SECONDS)
                        .take(count + 1)
                        .map(new Func1<Long, Long>() {
                            @Override
                            public Long call(Long aLong) {
                                return count - aLong;
                            }
                        })
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                setZNZCheck(true);
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Long>() {
                            @Override
                            public void onCompleted() {
                                //倒计时结束,如果还是监听状态，则自动异常
                                if (isZNZCheck()) {
                                    setZNZCheck(false);
                                    mView.closeDialog(true);
                                }

                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(Long o) {
                            }
                        });
                return;
            case "触摸功能":
                view = checkOnTouch();
                DialogCustomMode dialogCustomMode = new DialogCustomMode(name, view);
                dialogCustomMode.setShowBottomBtn(false);
                mView.showNobottomDialog(dialogCustomMode);
                return;
            case "按键功能":
                inflate = getInflate();
                inflate.tvFucation.setText("请按音量“+”键");
                inflate.imgIcon.setImageResource(R.mipmap.icon_audio_add);
                view = inflate.rootView;
                setVolumekeyUP(true);
                break;
            case "距离传感器":
                inflate = getInflate();
                inflate.tvFucation.setText("请用手遮挡手机顶部传感器位置");
                inflate.imgIcon.setImageResource(R.mipmap.icon_sereen_dric);
                view = inflate.rootView;
                setSenser(true);
                break;
            case "蓝牙":
                if (isDetectOver) {
                    //检测完成，选择
                    mView.showAnyDialog(attrBean);
                    return;
                }
                inflate = getInflate();
                inflate.tvFucation.setText("请打开蓝牙开关");
                inflate.imgIcon.setImageResource(R.mipmap.icon_bluetooth_dirc);
                view = inflate.rootView;

                CheckBluetooth(name, view);
                return;
//            case "充电功能":
//                inflate = getInflate();
//                inflate.tvFucation.setText("请插上充电线进行检测");
//                inflate.imgIcon.setImageResource(R.mipmap.icon_charge_dirc);
//                view = inflate.rootView;
//
//                checkChargeing(name, view);
//                return;

            case "指纹":
                inflate = getInflate();
                inflate.tvFucation.setText("请将手指放在手指指纹处");
                inflate.imgIcon.setImageResource(R.mipmap.icon_fingerprint_dric);
                inflate.setFingerprint.setVisibility(View.VISIBLE);
                view = inflate.rootView;
                try {
                    FingerprintIdentify fingerprintIdentify = new FingerprintIdentify((NewDetectActivity) context);
                    if (fingerprintIdentify.isHardwareEnable()) {
                        checkFingerprint(name, view);
                    } else {
                        mView.showAnyDialog(attrBean);
                    }
                } catch (Exception e) {
                    mView.detectSuccess(1);
                }

                return;

            case "WIFI":
                if (isDetectOver) {
                    //检测完成，选择
                    mView.showAnyDialog(attrBean);
                    return;
                }

                inflate = getInflate();
                inflate.tvFucation.setText("请打开WIFI开关");
                inflate.imgIcon.setImageResource(R.mipmap.icon_wifi_dirc);
                view = inflate.rootView;
                checkWIFI(view);
                return;
            case "通话功能":
                view = LayoutInflater.from(context).inflate(R.layout.dialog_detect_call, null);
                //.......
                //童话功能
                checkCall(view);
                break;
            case "扬声器":

                if (Looper.myLooper() == null) {
                    //如果不这么会 抛出  Only one Looper may be created per thread
                    //  Looper.prepare();
                }

                view = LayoutInflater.from(context).inflate(R.layout.dialog_detect_tryagain, null);
                checkLoudspeaker(view);
                DialogCustomMode customMode = new DialogCustomMode(name, view);
                customMode.setShowBtnOk(true);
                customMode.setOkText("听到声音");
                customMode.setNoText("未听到声音");
                customMode.setNeedCountDown(false);
                mView.showDialog(customMode, false);
                return;
            case "屏幕显示":
                view = checkScreenView();
                DialogCustomMode dialogCustomMode1 = new DialogCustomMode(name, view);
                dialogCustomMode1.setShowBottomBtn(false);
                dialogCustomMode1.setScrreen(true);
                setScreenView(true);
                mView.showNobottomDialog(dialogCustomMode1);
//                mView.showAnyDialog(attrBean);
                return;
            case "摄像功能":
                checkCamera();
                return;
            case "闪光灯":
                if (isDetectOver) {
                    //检测完成，选择
                    mView.showAnyDialog(attrBean);
                    return;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        chekcStare();
                    }
                }, 500);

                return;
            case "陀螺仪":
                if (isDetectOver) {
                    //检测完成，选择
                    mView.showAnyDialog(attrBean);
                    return;
                }
                if (!TLY) {
                    mView.detectSuccess(0);
                    return;
                }
                //等待三秒，监听不到就是有问题
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        checkTLY();
                    }
                }, 500);


                return;
            case "开机情况":

                mView.detectSuccess(0);//开机情况默认为正常，不让用户选择
                return;
            case "手机账户":
                setAccount(true);
                mView.showAnyDialog(attrBean);
                return;
            case "存储容量":

                long availableInternalMemorySize = getTotalInternalMemorySize();
                String text = DeviceUtils.formatPhoneCardFileSize(availableInternalMemorySize, true);
                int i = 0;
                for (GoodsBjgz.AttrBean.ValuesBean valuesBean : attrBean.getValues()) {
                    if (!TextUtils.isEmpty(text) && valuesBean.getName().equals(text)) {
                        mView.detectSuccess(i);
                        return;
                    }
                    i++;
                }
                mView.showAnyDialog(attrBean);
                return;
            default:
                //其他检测项目
                mView.showAnyDialog(attrBean);
                return;
        }
        mView.showDialog(new DialogCustomMode(name, view), true);

    }

    private void checkTLY() {
        final int count1 = 3;
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count1 + 1)
                .map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        return count1 - aLong;
                    }
                })
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        setTLYChekc(true);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted() {
                        //倒计时结束,如果还是监听状态，则自动异常
                        if (isTLYChekc()) {
                            mView.closeDialog(true);
                            setTLYChekc(false);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Long o) {
                    }
                });
    }

    private void checkChargeing(String name, View view) {
        if (NewDetectActivity.chargeStatus == BatteryManager.BATTERY_STATUS_CHARGING || NewDetectActivity.chargeStatus == BatteryManager.BATTERY_STATUS_FULL) {
            //正在充电或者电量满格
            mView.detectSuccess(0);//检测到成功
        } else {

            mView.showDialog(new DialogCustomMode(name, view), true);
            setChargeListener(true);
        }
    }

    /**
     * 指纹检测
     *
     * @param view
     */
    public void checkFingerprint(String name, View view) {
        mName = name;
        mView1 = view;
        mFingerprintIdentify = new FingerprintIdentify((NewDetectActivity) context);
        //首先判断是否支持指纹
        if (mFingerprintIdentify.isHardwareEnable()) {
            //指纹可用并且硬件可用
            mView.showDialog(new DialogCustomMode(name, view), true);
            if (!mFingerprintIdentify.isRegisteredFingerprint()) {
                mView.showToast("请先设置指纹");
            }
            //开始识别
            mFingerprintIdentify.startIdentify(10, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    mView.showToast("验证成功");
                    mView.detectSuccess(0);
                    setSeeting(false);
                    mView.closeDialog(false);
                    CloseFingerprintIdentify();
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    mView.showToast("没有匹配的指纹，还剩" + availableTimes + "次");
                }

                @Override
                public void onFailed() {

                    mView.showToast("验证失败");
                    if (!isPause) {
                        setSeeting(false);
                        mView.detectSuccess(1);
                        mView.closeDialog(false);
                    }


                }
            });
        } else {
            //不支持或者硬件损坏
            mView.detectSuccess(0);
            setSeeting(false);
            mView.closeDialog(false);
        }
    }

    public void CloseFingerprintIdentify() {
        if (mFingerprintIdentify != null && mFingerprintIdentify.isFingerprintEnable()) {
            mFingerprintIdentify.cancelIdentify();
        }


    }


    /**
     * 麦克风检测
     */
    private void checkVideo() {

        try {
            RecordButton recordButton = new RecordButton();
            recordButton.setDefaultFilePath(context);
            recordButton.setOnFinishedRecordListener(new RecordButton.OnFinishedRecordListener() {
                @Override
                public void onRecordFail() {
                    mView.detectSuccess(1);
                }

                @Override
                public void onStartRecordSuccess() {
                    mView.detectSuccess(0);
                }
            });
            recordButton.startRecording();
        } catch (Exception e) {
            mView.detectSuccess(1);
        }


    }

    /**
     * 闪光灯
     */
    private void chekcStare() {

        PackageManager packageManager = context.getPackageManager();
        if (!isSupportCameraLedFlash(packageManager)) {
            mView.detectSuccess(0);
            return;
        }
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            mView.detectSuccess(1);
        } else {


            mView.openLinght();


        }


    }

    public static boolean isSupportCameraLedFlash(PackageManager pm) {
        if (pm != null) {
            FeatureInfo[] features = pm.getSystemAvailableFeatures();
            if (features != null) {
                for (FeatureInfo f : features) {
                    if (f != null && PackageManager.FEATURE_CAMERA_FLASH.equals(f.name))
                        return true;
                }
            }
        }
        return false;
    }


    /**
     * 检查摄像功能
     */
    public void checkCamera() {
        //首先调取前置摄像头
        if (context != null)
            context.startActivity(new Intent(context, CommerActivity.class));

//       mView.openCamera(2);
    }

    /**
     * 检查扬声器
     *
     * @param view
     */
    public void checkLoudspeaker(View view) {
        Random random = new Random();

        soundIndex = random.nextInt(9);
        //初始化布局
        TextView tvTryagain = (TextView) view.findViewById(R.id.tvTryagain);


        tvTryagain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //再听一次
                playSound();

            }
        });

        //播放音频文件

        playSound();

    }

    public void playSound() {
        CommUtils.playSoundByMedia(context, sounds[soundIndex]);
    }

    /**
     * 检查通话
     *
     * @param view
     */
    public void checkCall(View view) {
        TextView tv_facation = (TextView) view.findViewById(R.id.tv_facation);
        final EditText et = (EditText) view.findViewById(R.id.et);
        TextView tvOk = (TextView) view.findViewById(R.id.tvOk);

        tv_facation.setText("请输入电话号码拨号");
        et.setText("112");
        tvOk.setText("拨号");
        tvOk.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View view) {
                //拨打电话
                if (Tools.isEmpty(et.getText().toString())) {
                    UITools.toastShowShort(context, "请输入号码");
                    return;
                }


                CommUtils.startCall(context, et.getText().toString());
                setCallListener(true);


            }
        });

    }

    /**
     * 触摸功能
     *
     * @return
     */
    public View checkOnTouch() {
        Fucation inflate = getInflate();
        inflate.tvFucation.setText("沿画面中格子划线，视填充格子判断正常与否");
        inflate.imgIcon.setImageResource(R.mipmap.icon_sereen_dric);
        inflate.onCheckonTouch.setVisibility(View.VISIBLE);
        inflate.onCheckonTouch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MDRouters.Builder().build("jiuji://ontouch").create(context.getApplicationContext()).go();
            }
        });


        return inflate.rootView;
    }


    /**
     * 检查蓝牙是否可用
     *
     * @param title
     * @param view
     */
    @SuppressLint("MissingPermission")
    public void CheckBluetooth(String title, View view) {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
            mView.detectSuccess(1);
            return;
        }

        if (mBluetoothAdapter.isEnabled()) {

            mView.detectSuccess(0);

        } else {
            setBlotetooh(true);
            mView.showDialog(new DialogCustomMode(title, view), true);

        }
    }

    /**
     * 屏幕显示功能
     *
     * @return
     */
    public View checkScreenView() {
        Fucation inflate = getInflate();
        inflate.tvFucation.setText("点击屏幕切换背景色");
        inflate.imgIcon.setImageResource(R.mipmap.icon_sereen_dric);
        inflate.onCheckonTouch.setVisibility(View.VISIBLE);
        inflate.onCheckonTouch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setClickScreen(true);
                new MDRouters.Builder().build("jiuji://screenView").create(context.getApplicationContext()).go();
            }
        });


        return inflate.rootView;
    }

    /**
     * 自动检测
     *
     * @return
     */

    public Fucation getInflate() {
        Fucation fucation = new Fucation();
        fucation.rootView = LayoutInflater.from(context).inflate(R.layout.dialog_detect_base_fucation, null);
        fucation.tvFucation = (TextView) fucation.rootView.findViewById(R.id.tv_facation);
        fucation.imgIcon = (ImageView) fucation.rootView.findViewById(R.id.iv_icon);
        fucation.setFingerprint = fucation.rootView.findViewById(R.id.ll_set_fingerprint);
        fucation.onCheckonTouch = fucation.rootView.findViewById(R.id.tv_check_ontouch);

        fucation.rootView.findViewById(R.id.tv_seeting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到设置
                setSeeting(true);
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                context.startActivity(intent);


            }
        });


        return fucation;
    }

    public class Fucation {
        public View rootView;
        public TextView tvFucation;
        public ImageView imgIcon;
        /**
         * 指纹
         */
        View setFingerprint;

        View onCheckonTouch;

    }

    public void checkGPS(final String title, final View view) {
        //检测权限

        boolean gpsEnable = DeviceUtils.isGPSEnable(context);
        //gps打开
        if (gpsEnable) {
            //gps正常，position为当前检测项对应的下标，需后台更改
            mView.detectSuccess(0);

        } else {
            mView.showDialog(new DialogCustomMode(title, view), true);
            setGPSListener(true);
            DeviceUtils.setGPSEnable(context, true);
        }

    }


    /**
     * 检测wifi模块
     *
     * @return
     */
    public void checkWIFI(final View view) {


        //判断wifi是否打开
        boolean wifiEnabled = NetworkUtils.getWifiEnabled(context);
        if (!wifiEnabled) {
            //没有打开wifi，弹出窗口，提醒用户打开
            mView.showDialog(new DialogCustomMode("WIFI检测", view), true);
            setWifiListener(true);//设置为wifi监听状态
        } else {

            checkWifiGood();

        }

    }

    /**
     * 检测wiifi是否正常（单独封装是方便监听调用）
     */
    public void checkWifiGood() {
        //检测
        if (DeviceUtils.isWifiIsGood(context)) {
            //wifi正常，position为当前检测项对应的下标，需后台更改
            mView.detectSuccess(0);
        } else {
            //wifi不正常
            mView.detectSuccess(1);
        }
    }


    public String getParamsString(List<GoodsBjgz.AttrBean> phoneAttr) {

        if (phoneAttr == null) {
            throw new RuntimeException("phone数据为空");
        }

        StringBuffer sBuffer = new StringBuffer();

        int size = phoneAttr.size();

        for (int i = 0; i < size; i++) {

            if (i != size - 1) {
                sBuffer.append(phoneAttr.get(i).getParams() + ",");
            } else {
                sBuffer.append(phoneAttr.get(i).getParams());
            }
        }


        System.out.println(sBuffer);
        return sBuffer.toString();
    }


}
